package com.scyshkj.university.wechat.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * 用于生成参数错误的返回数据
 * Created by 唐旭 on 2015/11/20.
 */
public abstract class BindingResultUtils {
    private static final String MESSAGE_SPLIT = "<br/>";

    private BindingResultUtils() {
    }

    public static <T extends ErrorJsonDto> T buildErrorMessage(BindingResult result, ErrorJsonDto jsonDto) {
        return buildErrorMessage(result, true, jsonDto);
    }

    @SuppressWarnings("unchecked")
    public static <T extends ErrorJsonDto> T buildErrorMessage(BindingResult result, boolean appendSplit, ErrorJsonDto jsonDto) {
        jsonDto.setMessage(buildErrorMessageAsString(result, appendSplit));
        return (T) jsonDto;
    }

    public static String buildErrorMessageAsString(BindingResult result, boolean appendSplit) {
        StringBuilder builder = new StringBuilder();
        List<ObjectError> allErrors = result.getAllErrors();
        for (ObjectError allError : allErrors) {
            builder.append(allError.getDefaultMessage());
            if (appendSplit) {
                builder.append(MESSAGE_SPLIT);
            }
        }
        return builder.toString();
    }
}